package parsers.teacher;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import parsers.CommonMethods;

import net.htmlparser.jericho.Element;
import net.htmlparser.jericho.HTMLElementName;
import net.htmlparser.jericho.Source;

import model.teacher.Department;
import model.teacher.Teacher;

public class TeachersParser
{	
	private Department department;
	
	public TeachersParser(Department department) 
	{
		this.department = department;
	}
	
	public ArrayList<Teacher> parse(boolean linkWithParent) throws IOException
	{
		ArrayList<Teacher> teachers = new ArrayList<Teacher>();
		
		Source source = new Source(new URL(department.getLink()));		
		List<Element> elements = source.getAllElements(HTMLElementName.TR);
		
		for (Element element : elements)
		{
			String name = element.toString();
			
			if(name.contains("bgcolor"))
			{
				List<Element> subElements = element.getAllElements(HTMLElementName.TD);
				for (int i = 0; i < subElements.size() - 1; i++)
				{
					List<Element> linkElements = subElements.get(i).getAllElements(HTMLElementName.A);
					for (Element linkElement : linkElements) 
					{
						String link = linkElement.getAttributeValue("href");
						if (link==null) 
							continue;
						String teacherName = linkElement.getContent().getTextExtractor().toString();
						String unitName = subElements.get(i + 1).getContent().toString();
						
						Teacher teacher = null;
						if(linkWithParent)
						{
							teacher = department.createTeacher(teacherName, unitName);
						}
						else
						{
							teacher = new Teacher(teacherName, unitName);
						}
						
						teacher.setLink(CommonMethods.parseLink(link));
						teachers.add(teacher);
					}
				}				
			}
		}

		return teachers;
	}
	
	/*public static void main(String[] args) throws MalformedURLException, IOException
	{
		Department d = new Department("Wydział Elektrotechniki, Informatyki i Telekomunikacji");
		d.setLink("file:/D:/test5.html");
		
		TeachersParser tp = new TeachersParser(d);
		ArrayList<Teacher> list = tp.parse(false);
		System.out.println(list);
	}*/
}
